<template>
  <div class="app-container">
    <div class="page-header">
      <div class="back-button">
        <el-button
          type="primary"
          @click="$router.push('/main/biao/pxqiandao')"
          icon="el-icon-back"
          >返回</el-button
        >
      </div>
      <h1>新员工入职培训签到列表</h1>
    </div>
    <!-- 搜索区域 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.trainer"
        placeholder="讲师姓名"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        type="success"
        icon="el-icon-plus"
        @click="handleCreate"
      >
        新增
      </el-button>
      <el-button
        :disabled="!selectedIds.length"
        class="filter-item"
        type="danger"
        icon="el-icon-delete"
        @click="handleBatchDelete"
      >
        批量删除
      </el-button>
      <!-- <el-button class="filter-item" type="primary" @click="goBack">返回</el-button> -->
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="讲师" prop="trainer" />
      <el-table-column label="培训日期" prop="trainingDate" width="180">
        <template slot-scope="{ row }">
          <span>{{ row.trainingDate | parseTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="参训人数"
        prop="totalStudents"
        width="100"
        align="center"
      />
      <el-table-column
        label="合格人数"
        prop="qualifiedStudents"
        width="100"
        align="center"
      />
      <el-table-column
        label="合格率"
        prop="passRate"
        width="100"
        align="center"
      >
        <template slot-scope="{ row }"> {{ row.passRate }}% </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button type="primary" size="mini" @click="handleView(row)">
            查看
          </el-button>
          <el-button type="success" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="danger" size="mini" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.current"
        :limit.sync="listQuery.size"
        @pagination="getList"
      />
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      :title="dialogStatus === 'create' ? '新增培训签到' : '编辑培训签到'"
      :visible.sync="dialogVisible"
    >
      <el-form
        ref="dataForm"
        :model="temp"
        :rules="rules"
        label-position="right"
        label-width="100px"
        style="width: 800px; margin-left: 50px"
      >
        <el-form-item label="培训讲师" prop="trainer">
          <el-input
            v-model="temp.trainer"
            :disabled="dialogStatus === 'view'"
          />
        </el-form-item>
        <el-form-item label="培训日期" prop="trainingDate">
          <el-date-picker
            v-model="temp.trainingDate"
            type="date"
            placeholder="选择日期"
            :disabled="dialogStatus === 'view'"
          />
        </el-form-item>

        <!-- 学员列表 -->
        <el-form-item label="学员列表">
          <el-table :data="temp.students" border style="width: 100%">
            <el-table-column
              label="序号"
              type="index"
              width="50"
              align="center"
            />
            <el-table-column label="姓名" prop="studentName">
              <template slot-scope="{ row }">
                <el-input
                  v-model="row.studentName"
                  :disabled="dialogStatus === 'view'"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="培训签到"
              prop="signIn"
              width="100"
              align="center"
            >
              <template slot-scope="{ row }">
                <el-switch
                  v-model="row.signIn"
                  :disabled="dialogStatus === 'view'"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="考核成绩"
              prop="score"
              width="100"
              align="center"
            >
              <template slot-scope="{ row }">
                <el-input-number
                  v-model="row.score"
                  :min="0"
                  :max="100"
                  :disabled="dialogStatus === 'view'"
                />
              </template>
            </el-table-column>
            <el-table-column
              v-if="dialogStatus !== 'view'"
              label="操作"
              width="100"
              align="center"
            >
              <template slot-scope="{ $index }">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="removeStudent($index)"
                />
              </template>
            </el-table-column>
          </el-table>
          <div v-if="dialogStatus !== 'view'" style="margin-top: 10px">
            <el-button type="primary" @click="addStudent">新增学员</el-button>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          v-if="dialogStatus !== 'view'"
          type="primary"
          @click="submitForm"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getTrainingSignPage,
  getTrainingSignDetail,
  saveTrainingSign,
  removeTrainingSigns,
} from "@/api/training";
import Pagination from "@/components/Pagination";

export default {
  name: "TrainingSignList",
  components: { Pagination },
  filters: {
    parseTime(time) {
      if (!time) return "";
      const date = new Date(time);
      if (isNaN(date.getTime())) return time;
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        current: 1,
        size: 10,
        trainer: undefined,
      },
      selectedIds: [],
      dialogVisible: false,
      dialogStatus: "",
      temp: {
        id: undefined,
        trainer: "",
        trainingDate: undefined,
        students: [],
      },
      rules: {
        trainer: [
          { required: true, message: "请输入培训讲师", trigger: "blur" },
        ],
        trainingDate: [
          { required: true, message: "请选择培训日期", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.listLoading = true;
      getTrainingSignPage(this.listQuery).then((response) => {
        this.list = response.data.records;
        this.total = response.data.total;
        this.listLoading = false;
      });
    },
    handleFilter() {
      this.listQuery.current = 1;
      this.getList();
    },
    handleSelectionChange(val) {
      this.selectedIds = val.map((item) => item.id);
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        trainer: "",
        trainingDate: undefined,
        students: [],
      };
    },
    handleCreate() {
      this.$router.push({
        path: "/main/biao/pxqiandao",
        query: {
          mode: "create",
        },
      });
    },
    goBack() {
      this.$router.push({
        path: "/main/biao/pxqiandao",
      });
    },
    handleView(row) {
      this.$router.push({
        path: "/main/biao/pxqiandao",
        query: {
          id: row.id,
          mode: "view",
        },
      });
    },
    handleUpdate(row) {
      this.$router.push({
        path: "/main/biao/pxqiandao",
        query: {
          id: row.id,
          mode: "edit",
        },
      });
    },
    handleDelete(row) {
      this.$confirm("确认删除该记录?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          removeTrainingSigns([row.id]).then(() => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getList();
          });
        })
        .catch(() => {});
    },
    handleBatchDelete() {
      this.$confirm(`确认删除选中的${this.selectedIds.length}条记录?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        removeTrainingSigns(this.selectedIds).then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getList();
        });
      });
    },
    addStudent() {
      this.temp.students.push({
        studentName: "",
        signIn: false,
        score: 0,
      });
    },
    removeStudent(index) {
      this.temp.students.splice(index, 1);
    },
    submitForm() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          // 验证学员信息
          if (!this.temp.students.length) {
            this.$message.error("请至少添加一名学员");
            return;
          }
          for (const student of this.temp.students) {
            if (!student.studentName) {
              this.$message.error("学员姓名不能为空");
              return;
            }
          }

          saveTrainingSign(this.temp).then(() => {
            this.$message({
              type: "success",
              message:
                this.dialogStatus === "create" ? "创建成功!" : "更新成功!",
            });
            this.dialogVisible = false;
            this.getList();
          });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 24px;
  // background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  min-height: calc(100vh - 48px);
  border-radius: 12px;
  // box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  width: 1200px;
  margin: 0 auto;
}
.page-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-bottom: 30px;
  padding: 20px;
  position: relative;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);

  h1 {
    font-size: 24px;
    color: #2c3e50;
    margin: 0;
    font-weight: 600;
    position: relative;
    padding-bottom: 10px;

    &::after {
      content: "";
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 60px;
      height: 3px;
      background: linear-gradient(90deg, #409eff, #67c23a);
      border-radius: 3px;
    }
  }
}

.back-button {
  position: absolute;
  left: 20px;
  top: 50%;
  transform: translateY(-50%);
}
.filter-container {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  gap: 12px;
  padding: 20px;
  margin-bottom: 20px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);

  .filter-item {
    margin: 0;
    &.el-input {
      width: 220px;
    }
    &.el-button {
      padding: 9px 20px;
      font-weight: 500;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
    }
  }
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);

  &::before {
    display: none;
  }

  .el-table__header-wrapper {
    th {
      background-color: #f8f9fa;
      color: #2c3e50;
      font-weight: 600;
      padding: 12px 0;
    }
  }

  .el-table__row {
    td {
      padding: 12px 0;
    }

    &:hover {
      td {
        background-color: #f5f7fa;
      }
    }
  }

  .small-padding {
    .el-button {
      padding: 6px 12px;
      margin: 0 4px;
    }
  }
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding: 20px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.el-dialog {
  border-radius: 12px;
  overflow: hidden;

  .el-dialog__header {
    padding: 20px;
    background: #f8f9fa;
    margin: 0;

    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #2c3e50;
    }
  }

  .el-dialog__body {
    padding: 24px;
  }

  .el-dialog__footer {
    padding: 16px 20px;
    border-top: 1px solid #ebeef5;
    background: #f8f9fa;
  }

  .el-form-item {
    margin-bottom: 24px;
  }

  .el-table {
    margin-bottom: 16px;
  }
}

@media screen and (max-width: 768px) {
  .app-container {
    padding: 16px;
  }

  .filter-container {
    padding: 16px;
    flex-direction: column;
    align-items: stretch;

    .filter-item {
      width: 100% !important;
    }
  }

  .el-dialog {
    width: 90% !important;
    margin: 5% auto !important;
  }
}
</style> 